package com.bawei.module_move

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_base.RoutePath
import com.bawei.lib_common.mvi.BaseMviFragment
import com.bawei.module_move.adapter.MovieViewPageAdapter
import com.bawei.module_move.databinding.FragmentMoveBinding
import com.bawei.module_move.state.MoveStates
import com.bawei.module_move.vm.MoveViewModel
import com.example.movie.entity.MovieTypeEntity
import com.example.movie.intent.MovieViewIntent
import com.google.android.material.tabs.TabLayoutMediator
import com.lxj.xpopup.XPopup
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
@Route(path = RoutePath.PATH_FRAGMENT_MOVIE)
class MoveFragment : BaseMviFragment<FragmentMoveBinding>() {

    //获取viewmodel
    private val  mviewmodel:MoveViewModel by activityViewModels()
    //获取搜索轮播图样式
    private var searchHints= mutableListOf("热门影视","今日电影","动作电影")
    //获取两个分类的实体类集合
    private var oneTypeList= mutableListOf<MovieTypeEntity>()
    private var twoTypeList= mutableListOf<MovieTypeEntity>()

    //获取下方fragment
    private var fragmentts= mutableListOf<MoveListFragment>()

    //获取适配器
    private lateinit var viewpageadapter:MovieViewPageAdapter
    private lateinit var mCPopupBuilder:XPopup.Builder

    private var leverOneTypeId=1
    override fun getLayoutId(): Int {
        return R.layout.fragment_move
    }

    override fun initViews() {

        //设置搜索中搜索热词
        mDatatBinding.tbvSearch.setDatas(searchHints)
        //关闭Popup组件

        //一级分类筛选
        mDatatBinding.tvFilter.setOnClickListener {
            showMovieTypeFile()
        }

        //创建ViewPagerAdapter
        viewpageadapter= MovieViewPageAdapter(fragmentts,childFragmentManager,lifecycle)
        mDatatBinding.vpVideo.apply {
            offscreenPageLimit=3
            adapter=viewpageadapter
        }

        //关联Tablayout与ViewPage2
        TabLayoutMediator(mDatatBinding.tabTypeLayout,mDatatBinding.vpVideo){
            tab,posion->
            tab.text=twoTypeList[posion].typename
        }.attach()

    }

    override suspend fun sendViewIntent() {
        super.sendViewIntent()
        mviewmodel.channel.send(MovieViewIntent.LoadLeverOneType)
    }

    override suspend fun collectUIState() {
        mviewmodel.uiStateFlow.collect{
            when(it){
                is MoveStates.LoadLeverOneTypeSuccess->initLeverPnePageWindow(it.list)
                is MoveStates.LoadLeverOneTypeFail->{

                }
                is MoveStates.LoadLeverTwoTypeSuccess->initLeveerTwoType(it.list)
                is MoveStates.LoadLeverTwoTypeFail->LoadTwoFail()
                else->{

                }
            }
        }

    }

    //二级分类获取失败
    private fun LoadTwoFail(){
        twoTypeList.clear()
        fragmentts.clear()
        mDatatBinding.tabTypeLayout.removeAllTabs()

        //添加推荐Tab
        twoTypeList.add(MovieTypeEntity(0,0,-1,0,"tuijian"
            ,"推荐"))
        fragmentts.add(
            ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_MOVIE_LIST).withInt("tabId",-1)
                .navigation() as MoveListFragment
        )
        //创建Tab标签
        twoTypeList.forEach {
            mDatatBinding.tabTypeLayout.addTab(mDatatBinding.tabTypeLayout.newTab()
                .setText(it.typename))
        }

        //更新数据
        mDatatBinding.vpVideo.adapter=viewpageadapter
        viewpageadapter.notifyDataSetChanged()
    }

    //二级分类获取成功
    private fun initLeveerTwoType(list:List<MovieTypeEntity>){
        if(list.isNotEmpty()){
            twoTypeList.clear()
            fragmentts.clear()
            mDatatBinding.tabTypeLayout.removeAllTabs()

            //添加推荐Tab
            twoTypeList.add(MovieTypeEntity(0,0,-1,0
                ,"tuijian","推荐"))
            fragmentts.add((ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_MOVIE_LIST)
                .withInt("tabId",-1).navigation()as MoveListFragment))
            //添加其他二级分类
            list.forEach {
                twoTypeList.add(it)
                fragmentts.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_MOVIE_LIST).withInt("tabId",it.id).navigation() as MoveListFragment)

            }
            //创建Tab标签
            twoTypeList.forEach {
                mDatatBinding.tabTypeLayout.addTab(mDatatBinding.tabTypeLayout.newTab().setText(it.typename))
            }
            //更新数据
            mDatatBinding.vpVideo.adapter=viewpageadapter
            viewpageadapter.notifyDataSetChanged()
        }
    }

    private fun initLeverPnePageWindow(list:List<MovieTypeEntity>){
        if(oneTypeList.size>0)oneTypeList.clear()
        oneTypeList.addAll(list)

        //加载二级分类
        lifecycleScope.launch {
            mviewmodel.channel.send(MovieViewIntent.LoadLeverTwoType(oneTypeList[0].id))
        }
    }



    private fun showMovieTypeFile() {
     if(oneTypeList.isNotEmpty()){
         var menuNameList= mutableListOf<String>()
         oneTypeList.forEach {
             menuNameList.add(it.typename)
         }
         mCPopupBuilder=XPopup.Builder(requireContext()).atView(mDatatBinding.cltFilter)
         mCPopupBuilder.autoDismiss(true)
         mCPopupBuilder.asAttachList(menuNameList.toTypedArray(),null){index,_ ->
             leverOneTypeId = oneTypeList[index].id
             //加载二级分类
             loadNewTwoTypeById()
         }.show()
     }
    }

    private fun loadNewTwoTypeById() {
        lifecycleScope.launch {
            mviewmodel.channel.send(MovieViewIntent.LoadLeverTwoType(leverOneTypeId))
        }
    }


}